<template>
	<section>
		<!--工具条 高级查询部分-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="keyword" placeholder="请输入关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="keywordQuery">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表
		  :data=  ：绑定的数据   highlight-current-row 高亮
		  v-loading：转圈圈  忙等框
		  @selection-change：选中改变的时候触发
		  sortable ： 表格排序
		-->
		<el-table :data="employees" highlight-current-row v-loading="listLoading"
              @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="username" label="姓名" width="120" sortable>
      </el-table-column>
      <el-table-column prop="phone" label="电话" width="140"  sortable>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="140" sortable>
      </el-table-column>
      <el-table-column prop="salt" label="盐值" width="120" sortable>
      </el-table-column>
      <el-table-column prop="password" label="密码" width="120" sortable>
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="120" sortable>
      </el-table-column>
      <el-table-column prop="shop.name" label="管理店铺" width="120" sortable>
      </el-table-column>
      <el-table-column prop="department.name" label="所属部门" width="120" sortable>
      </el-table-column>

      <el-table-column prop="state" label="是否启用" width="100" sortable>
        <template scope="scope">
          <el-span style="color: green" v-if="scope.row.state==1" size="small" >启用</el-span>
          <el-span style="color: red" v-else-if="scope.row.state==0" size="small" >禁用</el-span>
          <el-span style="color: gray" v-else size="small">未知</el-span>
        </template>
      </el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条：批量删除-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="totals" style="float:right;">
			</el-pagination>
		</el-col>

    <!--id: null,
    sn:'',
    name: '',
    state:1,
    manager_id: '',
    parent_id: ''-->
		<!--添加或修改的对话框-->
		<el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="70px" :rules="editFormRules" ref="editForm">
        <el-form-item label="姓名" prop="username">
          <el-input v-model="editForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="editForm.phone" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="盐值" prop="salt">
          <el-input v-model="editForm.salt" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="editForm.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="editForm.age" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工状态" prop="state">
          <el-radio-group v-model="editForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属部门" prop="department_id">
          <el-select v-model="editForm.department_id" placeholder="请选择">
            <!--          v-for="item in cities" for循环
                            :key="item.value"//唯一标识
                            :label="item.label"//展示的名字
                            :value="item.value" 传回后端的数据
                             -->
            <el-option
                v-for="item in departments"
                :label="item.name"
                :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.id }}</span
              >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="店铺" prop="shop_id">
          <el-select v-model="editForm.shop_id" placeholder="请选择">
            <el-option
                v-for="item in shops"
                :label="item.name"
                :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.id }}</span
              >
            </el-option>
          </el-select>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>


	</section>
</template>

<script>
	/*import util from '../../common/js/util'  //不需要引入外部文件，所以注释
	//import NProgress from 'nprogress'
	import { getEmployeeListPage, removeEmployee, batchRemoveEmployee, editEmployee, addEmployee } from '../../api/api';*/

	export default {
		data() {
			return {
				//1.数据列表相关模型数据
        departments: [],
        //查询所有商店
        shops:[],
        listLoading: false,

        //2.分页查询数据
				totals: 0,
				currentPage: 1,
				pageSize: 4,

        //3.高级查询
        keyword:'',

        //4.批量删除
				sels: [],//列表选中列

        //5.添加或修改
        title:'',
				editFormVisible: false,//添加或修改的界面是否显示
				editLoading: false,//提交按钮上的保存模态框
				editFormRules: {  //表单项验证规则
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				//编辑界面数据，建议字符串用'',id用null
				editForm: {
          id:null,
          username:'', phone:'', email:'', salt:'', password:'', age:null,
          state:'', department_id:null, logininfo_id:null, shop_id:null
				},




			}
		},
		methods: {

      getShops(){
        this.$http.get("/shop")
            .then(res=>{
              this.shops=res.data;
            })
      },
      getDepartments(){
        this.$http.get("/department")
            .then(res=>{
              this.departments=res.data;
            })
      },

			//1.获取用户列表
			getEmployees() {
				let para = {
          //第一个currentPage：发送到后端的参数 ， this.currentPage:本页面的data参数
					currentPage: this.currentPage,
          pageSize:this.pageSize,
          keyword:this.keyword,
					//name: this.filters.name//暂时不用，高级查询
				};
				//开启忙等框
				this.listLoading = true;
				//发送axios需求,注意语法！，$http.post  以及  res=>{}
        this.$http.post("/employee",para)
        .then(res=>{
          this.employees=res.data.data;
          this.totals=res.data.totals;
          this.listLoading = false;//关闭忙等框
        }).catch(res=>{
          this.$message.error("网络不稳定");
        })

			},
      //2.点击当前页的查询逻辑
      handleCurrentChange(val) {
        this.currentPage = val;
        this.getEmployees();

      },
      //3.高级查询
      keywordQuery(){
        this.currentPage=1;
        this.getEmployees();
      },

			//4.删除按钮
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {//确认框
					type: 'warning'
				}).then(() => {//点击确定的时候执行
					this.listLoading = true;
					//let para = { id: row.id };
          this.$http.delete("/employee/"+row.id).then(res=>{
            if(res.data.success){
              this.$message.success("删除成功");
              //处理当前页
              let totalPage = Math.ceil(this.totals/this.pageSize);//计算总页数
              //判断当前页是最后一页，且-1后整除pageSize，且不是第一页
              if(this.currentPage==totalPage && (this.totals-1)%this.pageSize==0 && this.currentPage!=1){
                this.currentPage=this.currentPage-1;
              }

              this.getEmployees();
            }else {
              this.$message.error("网络繁忙，500")
            }
          }).catch(res=>{
            this.$message.error("网络繁忙，404，400")
          })
				}).catch(() => {
				});
			},
      //5.批量删除选项改变时触发
      selsChange: function (sels) {
			  console.log(sels);
        this.sels = sels;
      },

      //6.批量删除,向后端发送请求
      batchRemove: function () {
        var ids = this.sels.map(item => item.id);//[1,2,3]
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          //let para = { ids: ids };
          this.$http.patch("/employee",ids).then(res=>{
            this.listLoading = false;
            if(res.data.success){
              this.$message.success("删除成功");//展示信息
              this.currentPage=1;//currentPage=1
              this.getEmployees();//展示第一页数据
            }else{
              this.$message.error("网络繁忙，稍后重试500");
            }
          }).catch(res=>{
            this.$message.error("网络繁忙，稍后重试500");
          })
        }).catch(() => {

        });
      },
      //7.点击新增显示对话框
      handleAdd: function () {

        this.editForm = {
          id:null,
          username:'', phone:'', email:'', salt:'', password:'', age:null,
          state:'', department_id:null, logininfo_id:null, shop_id:null
        };
        this.title= '新增部门';
        this.getDepartments();
        this.getShops();
        this.editFormVisible = true;
      },

			//8.点击修改按钮显示对话框
			handleEdit: function (index, row) {
        this.title= '修改部门信息';
        this.getDepartments();
        this.getShops();
				this.editFormVisible = true;
				//克隆一个假的数据对象，再赋值给 editForm
				this.editForm = Object.assign({}, row);
			},

			//9.提交添加或修改的数据
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {
					if (valid) {//表单验证通过
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
						  this.editLoading = true;
							let para = Object.assign({}, this.editForm);
							let arr = para.parent_id;
              if(arr && arr.length==0){
                para.parent_id=null;
              }
							if(arr && arr.length>0){
                para.parent_id=arr[arr.length-1];
              }

							this.$http.put("/employee",para).then(res=>{
                this.editLoading = false;
                this.editFormVisible = false;
                if(res.data.success){
                  this.$message.success("操作成功");//展示信息
                  //this.currentPage=1;//此处不需要重置页面
                  this.getEmployees();//展示第一页数据
                }else{
                  this.$message.error("网络繁忙，稍后重试500");
                }
              }).catch(res=>{
                this.$message.error("网络繁忙，稍后重试400");
              })
						});
					}
				});
			},
      //10.查询所有经理
      getManagers:function (){
          this.$http.get("/employee").then(res=>{
            this.managers=res.data;
          }).catch(res=>{
            this.$message.error("无法获取经理信息")
          })
      },




		},
		mounted() {
			this.getEmployees();
		}
	}

</script>

<style scoped>

</style>